package com.djx.CRUD;

import com.djx.utils.MongoDBUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class Delete {

    MongoDBUtil util = MongoDBUtil.getInstance();
    MongoDatabase database = util.getDatabase("d01");
    MongoCollection<Document> collection = database.getCollection("c1");

    /**
     * 删除单条数据
     */
    @Test
    public void TestDeleteOne() {
        BasicDBObject map = new BasicDBObject();
        map.put("name", "姚乐乐1");
        map.put("age", 21);
        map.put("sex", "女1");
        map.put("city", "石家庄1");
        collection.deleteOne(map);
        System.out.println("删除成功");
        util.closeDB();
    }

    /**
     * 删除多数据
     */
    @Test
    public void TestDeleteMany() {
        BasicDBObject map = new BasicDBObject();
        map.put("name", "姚乐乐1");
        map.put("age", 21);
        map.put("sex", "女1");
        map.put("city", "石家庄1");
        collection.deleteMany(map);
        System.out.println("删除成功");
        util.closeDB();
    }

    /**
     * Filters One 当出现筛选条件查出多条数据时，只会删除符合条件的第一条(先后顺序)，如以下代码
     */
    @Test
    public void FiltersDeleteOne() {
        List<Bson> list = new ArrayList<>();
        list.add(Filters.eq("name","姚乐乐1"));
        list.add(Filters.eq("age",21));
        Bson bson = Filters.and(list);

        collection.deleteOne(bson);
        System.out.println("删除成功");
        util.closeDB();
    }
    /**
     * Filters
     */
    @Test
    public void FiltersDeleteMany() {
        List<Bson> list = new ArrayList<>();
        list.add(Filters.eq("name","姚乐乐1"));
        list.add(Filters.eq("age",21));
        Bson bson = Filters.and(list);
        collection.deleteMany(bson);
        System.out.println("删除成功");
        util.closeDB();
    }


}
